
import json
from flask import Flask,jsonify,request,redirect
from datab import db
from myjwt import myjwt
import time
import requests
app = Flask(__name__)


# @app.route("/test")
# def test():
#     res = requests.post("http://localhost:5000/login",{'name':'zs','password':'123'})
#     print(res.text)
#     return 'ok11'


@app.route("/login",methods=['POST'])
def login():
    name = request.form.get("name")
    password = request.form.get('password')
    if not all([name,password]):
        return jsonify({"code":10010,"mes":"必须输入用户名和密码"})
    #获取用户名密码去数据库中对比
    sql = "select * from user where name='%s' and password='%s'"%(name,password)
    user = db.findOne(sql)
    if user:
        time1 = int(time.time())+3600
        data={'data':{"userid":user['id'],'exp':time1}}
        token = myjwt.jwt_en(data)
        #token过期刷新token使用
        time2 = int(time.time())+7200
        data1={'data':{"userid":user['id'],'exp':time2}}
        retoken = myjwt.jwt_en(data1)
        return jsonify({"code":200,'token':token,'retoken':retoken})
    else:
        #成功生成token返回
        return jsonify({"code":10011,'mes':'用户认证失败'})

#刷新token
@app.route("/retoken",methods=['POST'])
def retoken():
    retoken = request.form.get("retoken")
    try:
        payload = myjwt.jwt_de(retoken)
        time1 = payload['data']['exp']
        if time1<int(time.time):
            return jsonify({"code":20011,'mes':'retoken已过期'})
        else:
            time1 = int(time.time())+3600
            data = {"data":{"userid":payload['data']['userid'],"exp":time1}}
            token = myjwt.jwt_en(data)

            time2 = int(time.time())+7200
            data1={'data':{"userid":payload['data']['userid'],'exp':time2}}
            retoken = myjwt.jwt_en(data1)
            return jsonify({"code":200,'token':token,'retoken':retoken})
    except:
        return jsonify({"code":20010,'mes':'retoken被修改'})

import functools
#用装饰器实现token认证


def islogin(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        #验证是否登录，是否过期等
        try:
            token = request.args.get('token')
            flag = myjwt.jwt_check(token)
            if flag == True:
                #过期时间
                payload = myjwt.jwt_de(token)
                if int(payload['data']['exp']) < int(time.time()):
                    return jsonify({"code":402,"mes":"已经过期"})
            else:
                return jsonify({"code":401,"mes":"被修改"})
        except:
            return jsonify({"code":403,"mes":"没有权限操作"})
        return func(*args,**kwargs)
    return wrapper





@app.route("/open_bank")
@islogin
def open_bank():
    # #获取开户信息 身份证号、银行卡号、手机号、id、url
    url=request.args.get('redirect_uri')
    id = 1
    # sql1 = "select id from bank where bank_code='%s' and code='%s' and mobile='%s'"%(i['bank_code'],i['code'],i['mobile'])
    # res1 = db.findOne(sql1)
    res1=11
    if res1:
        #  sql1="insert into open_bank(bankid,code,username,bank_code,mobile,url,status) values(%d,'%s','%s','%s','%s','%s',%d)"%(int(id),code,name,bankcode,mobile,url,1)
        #  db.update(sql1)
         url=url+'?id=1&status=1'
    else:
        url=url+'?id=1&status=2'
    # id = request.args.get('id')
    # code = request.args.get('code')
    # name = request.form.get('name')
    # bankcode = request.form.get('bankcode')
    # mobile = request.form.get('mobile')
    # if not all([id,code,bankcode,mobile,url]):
    #     return jsonify({"code":2001,'mes':"参数错误"})

    # sql1="insert into open_bank(bankid,code,username,bank_code,mobile,url,status) values(%d,'%s','%s','%s','%s','%s',%d)"%(int(id),code,name,bankcode,mobile,url,1)
    # db.update(sql1)
    return redirect(url)
    
  

@app.route("/checkbankcode") 
def checkbankcode():
    sql = "select * from open_bank where status=1 order by id asc"
    res = db.findAll(sql)
    for i in res:
        sql1 = "select id from bank where bank_code='%s' and code='%s' and mobile='%s'"%(i['bank_code'],i['code'],i['mobile'])
        res1 = db.findOne(sql1)
        if res1:
            usql="update open_bank set status=%d where id=%d"%(2,i['id'])
            db.update(usql)
            requests.get(i['url'])
        else:
            usql="delete from open_bank where id=%d"%(i['id'])
            db.update(usql)



    
#用装饰器实现token认证  
@app.route("/checktoken") 
@islogin
def checktoken():
    print("&&&&")
    return jsonify({"code":200})


@app.route("/test") 
def test():
    time1 = int(time.time())-3600
    data={'data':{"userid":1,'exp':time1}}
    token = myjwt.jwt_en(data)

    data={'id':1,'code':'1665567788','name':'zs','bankcode':'622234245245','mobile':'1821098766'}
    res = requests.post("http://localhost:5000/open_bank",data=data,headers={"token":token})
    print(res.text)
    return 'ok'

if __name__=="__main__":
    app.run(debug=True)